<template>
  <div ref="flowFrawerContainer" :class="['flow-drawer']"/>
</template>
<script setup>
import {computed, nextTick, onMounted, shallowRef} from 'vue';
import bindResize from '@/components/FlowDrawer/bindResize';
import GraphFactory from '@/components/FlowDrawer/GraphFactory';
import FlowDrawerSupport from '@/components/FlowDrawer/FlowDrawerSupport';

defineOptions({
  name: 'FlowDrawer'
});
const flowFrawerContainer = shallowRef();
let graph = null;
const props = defineProps({
  modelValue: {
    type: String,
    default: undefined
  }
});
const emits = defineEmits(['update:modelValue']);
const flowModel = computed({
  get() {
    if (!props.modelValue || props.modelValue === '') {
      emits('update:modelValue', JSON.stringify(FlowDrawerSupport.getInitFlow()));
      return FlowDrawerSupport.getInitFlow();
    }
    return JSON.parse(props.modelValue);
  },
  set(value) {
    emits('update:modelValue', JSON.stringify(value));
  },
});

function reRender() {
  nextTick(() => {
    graph.read(JSON.parse(JSON.stringify(flowModel.value)));
  })
}

function createGraph() {
  if (!flowFrawerContainer.value) return;
  flowFrawerContainer.value.innerHTML = '';
  graph = GraphFactory.createGraph(flowFrawerContainer.value);
  graph.renderFlowModel = () => reRender();
  graph.flowModel = flowModel;
  graph.renderFlowModel();
}

onMounted(() => {
  nextTick(() => {
    bindResize(flowFrawerContainer.value, 200, () => createGraph());
  });
});
</script>
<style lang="scss">
@import 'flow-drawer';
</style>